package com.sservice.web.controller.admin;

import com.alibaba.fastjson.JSONObject;
import com.sservice.banfu.e.Tpl;
import com.sservice.banfu.service.TplService;
import com.sservice.base.Arith;
import com.sservice.base.SameUrlData;
import com.sservice.base.StringUtils;
import com.sservice.base.entity.dto.BaseResult;
import com.sservice.base.entity.dto.ListResult;
import com.sservice.base.entity.dto.Pagination;
import com.sservice.common.Constants;
import com.sservice.commonBusiness.e.Category;
import com.sservice.commonBusiness.e.DataR;
import com.sservice.commonBusiness.service.CategoryService;
import com.sservice.commonBusiness.service.DataRService;
import com.sservice.commonBusiness.service.FileService;
import com.sservice.commonBusiness.type1.DataR_TYPE;
import com.sservice.commonBusiness.vo.DataRVo;
import com.sservice.commonBusiness.vo.FileVo;
import com.sservice.model.dao.OfferVarsMapper;
import com.sservice.model.entity.Offer;
import com.sservice.model.entity.OfferVars;
import com.sservice.model.entity.Order;
import com.sservice.model.vo.OfferVo;
import com.sservice.model.vo.ShopifyParam;
import com.sservice.service.service.IOfferService;
import com.sservice.service.service.IOrderService;
import com.sservice.service.service.ISysLogService;
import com.sservice.urp.vo.UserVo;
import com.sservice.web.log.Action;
import com.sservice.web.wx.AdvancedUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

/**
 * 商品
 */
@Controller
@RequestMapping("/admin/offer")
public class OfferController {
//    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    OfferVarsMapper offerVarsMapper;
    @Autowired
    FileService fileService;
    @Autowired
    TplService tplService;
    @Autowired
    CategoryService categoryService;
    @Autowired
    DataRService dataRService;
    @Autowired
    private IOfferService depService;
    //    @Autowired
//    private IGoodsService goodsService;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private ISysLogService sysLogService;

    @RequestMapping(value = "/category/add", method = RequestMethod.POST)
    @ResponseBody
    public BaseResult add(Category category, HttpSession session) {
        UserVo user = (UserVo) session.getAttribute(Constants.USER);

        if ("coupon".equals(category.getType1()) || "gift".equals(category.getType1())) {
            category.setEn(Constants.generateDataNo("",
                    "gift".equals(category.getType1()) ? Constants.NO_DATA_TYPE_GIFT : Constants.NO_DATA_TYPE_COUPON,
                    user.getId() + ""));
        }
        categoryService.insertSelective(category);
        return new BaseResult(true, category);
    }

    /**
     * 创建
     *
     * @return
     */
    @SameUrlData
    @ResponseBody
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public BaseResult<Object> create(@ModelAttribute OfferVo arg, HttpSession session, HttpServletRequest request) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        UserVo user = (UserVo) session.getAttribute(Constants.USER);
        BaseResult<Object> res = null;
        arg.setCreatorId(String.valueOf(user.getId()));
        arg.setCreator(user.getUserName());
        arg.setPrice(arg.getPrice());//
        Tpl tpl = new Tpl();
        tpl.setContent(arg.getDetail().getBytes());
        tpl.setType1("");
        tplService.save(tpl);
        arg.setDetail(tpl.getId().toString());
        int service_res = depService.insertSelective(arg);

        List<OfferVars> list = arg.getVars();
        if (list != null && list.size() != 0) {
            for (OfferVars ov : list) {
                ov.setOfferId(arg.getId().toString());
            }
            offerVarsMapper.deleteBatch(arg.getId());// 批量删除
            offerVarsMapper.addBatch(list); // 批量增加
        }
        if (!StringUtils.isBlank(arg.getFileIds())) {
            String[] ids = arg.getFileIds().split(",");
            List list2 = new ArrayList();
            for (String id : ids) {
                DataR dataR = new DataR();
                dataR.setTargetId(Integer.valueOf(id));
                dataR.setSourceId(arg.getId());
                dataR.setType1(DataR_TYPE.TYPE_SHOP_BANNER.getValue());
                list2.add(dataR);
            }
            dataRService.addBatch(list2);
        }


        if (service_res > 0) {
            sysLogService.log("创建", request, Integer.valueOf(arg.getId()), Action.offerType);
        }
        res = new BaseResult(true, service_res);
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "/getCategoryByRecord", method = RequestMethod.GET)
    public ListResult getCategoryByRcecord(OfferVo record) {
//        List<Category> list = depService.getCategoryByRcecord(record);
        return new ListResult(true, null);
    }

    /**
     * 基本信息
     *
     * @param arg
     * @return
     * @throws NoSuchMethodException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     */
    @SameUrlData
    @ResponseBody
    @RequestMapping(value = "/get", method = RequestMethod.GET)
    public BaseResult<Object> get(Offer arg) {
        return new BaseResult(true, depService.selectByPrimaryKey(arg.getId()));
    }

    /**
     * 详情
     *
     * @param arg
     * @return
     * @throws NoSuchMethodException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     */
    @SameUrlData
    @ResponseBody
    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    public BaseResult<Object> detail(Offer arg) {
        OfferVo ov = depService.selectByPrimaryKey(arg.getId());
        if (OfferVo.MULTI_VARS_MULTI_VARS.equals(ov.getMultiVars())) { // 多规格商品
            OfferVars offerVars = new OfferVars();
            offerVars.setOfferId(ov.getId().toString());//
            ov.setVars(offerVarsMapper.selectBy(offerVars));// 多规格
        }

        FileVo fileVo = new FileVo();
        fileVo.setDataRtype1("shop-banner");
        fileVo.setSourceId(ov.getId().toString());//
        ov.setFiles(fileService.selectByDataR(fileVo));
        ov.setDetail(new String(tplService.selectById(Integer.valueOf(ov.getDetail())).getContent()));//初始化
        return new BaseResult(true, ov);
    }

    @ResponseBody
    @RequestMapping(value = "/shopify-post", method = RequestMethod.POST)
    public JSONObject shopifyPost(ShopifyParam param, String url) {
        return AdvancedUtil.httpsRequestWithUserAndPass("https://bytedevstore.myshopify.com/" + url,
                "POST", "{\"available_adjustment\":\"1\",\"inventory_item_id\":\"18228580778095\",\"location_id\":\"14512160879\"}", Constants.apikey, Constants.apiPs);
    }

    @ResponseBody
    @RequestMapping(value = "/shopify", method = RequestMethod.GET)
    public JSONObject shopify(String url) {
        return AdvancedUtil.httpsRequestWithUserAndPass("https://bytedevstore.myshopify.com/" + url,
                "GET", null, Constants.apikey, Constants.apiPs);
    }

    /**
     * 批量增加关系
     *
     * @param dataRVo
     * @param session
     * @param request
     * @return
     * @throws NoSuchMethodException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     */
    @SameUrlData
    @ResponseBody
    @RequestMapping(value = "/addDataR", method = RequestMethod.POST)
    public BaseResult<Object> dataR(DataRVo dataRVo, HttpSession session, HttpServletRequest request) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        DataRVo dataRVo1 = new DataRVo();
        dataRVo1.setType1(dataRVo.getType1());
        dataRVo1.setSourceId(dataRVo.getSourceId());
        dataRService.delBy(dataRVo1);

        String[] list = dataRVo.getIds().split(",");
        List list1 = new ArrayList();
        for (int i = 0; i < list.length; i++) {
            DataR dataR = new DataR();
            dataR.setType1(dataRVo.getType1());
            dataR.setSourceId(dataRVo.getSourceId());
            dataR.setTargetId(Integer.valueOf(list[i]));
            list1.add(dataR);
        }
        return new BaseResult(true, dataRService.addBatch(list1));
    }

    /***
     * 增加可售数量
     * @param arg
     * @param session
     * @param request
     * @return
     * @throws NoSuchMethodException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     */
    @SameUrlData
    @ResponseBody
    @RequestMapping(value = "/plus", method = RequestMethod.POST)
    public BaseResult<Object> plus(Offer arg, HttpSession session, HttpServletRequest request) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {

        Offer offer = depService.selectByPrimaryKey(Integer.valueOf(arg.getId()));
        Double number = arg.getSaleNum();
        UserVo user = (UserVo) session.getAttribute(Constants.USER);


        arg.setSaleNum(Arith.add(arg.getSaleNum(), offer.getSaleNum()));
        int service_res = depService.updateByPrimaryKeySelective(arg);


        BaseResult<Object> res = new BaseResult(true, service_res);
        return res;
    }

    /**
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public BaseResult<Object> delete(Offer arg, HttpServletRequest request) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        arg.setStatus("3"); //逻辑删除
        Order order = new Order();
        order.setOfferId(arg.getId().toString());
        int service_res = depService.updateByPrimaryKeySelective(arg);
        if (service_res > 0) {
            sysLogService.log("删除", request, Integer.valueOf(arg.getId()), Action.offerType);
        }
        return new BaseResult(true, service_res);
    }

    /**
     * 通过订单ID
     *
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getByOrderId", method = RequestMethod.GET)
    public BaseResult<Object> getByOrderId(Order arg) {
        Order service_res = orderService.selectByPrimaryKey(arg.getId());
        Offer offer = depService.selectByPrimaryKey(Integer.valueOf(service_res.getOfferId()));
        return new BaseResult(true, offer);
    }

    /**
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public BaseResult update(OfferVo arg, HttpSession session, HttpServletRequest request) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        UserVo user = (UserVo) session.getAttribute(Constants.USER);
        BaseResult<Object> res = null;
        arg.setCreatorId(String.valueOf(user.getId()));
        arg.setCreator(user.getUserName());
//        arg.setPrice(arg.getActualPrice());//

        Offer offer = depService.selectByPrimaryKey(arg.getId());
        Tpl tpl = tplService.selectById(Integer.valueOf(offer.getDetail()));
        tpl.setContent(arg.getDetail().getBytes());
        tplService.update(tpl);
        arg.setDetail(offer.getDetail());
        depService.updateByPrimaryKeySelective(arg);
        List<OfferVars> list = arg.getVars();
        if (list != null && list.size() != 0) {
            for (OfferVars ov : list) {
                ov.setOfferId(arg.getId().toString());
            }
            offerVarsMapper.deleteBatch(arg.getId());// 批量删除
            offerVarsMapper.addBatch(list); // 批量增加
        }
        if (!StringUtils.isBlank(arg.getFileIds())) {
            String[] ids = arg.getFileIds().split(",");
            List list2 = new ArrayList();
            DataR dataR1 = new DataR();
            dataR1.setSourceId(arg.getId());
            dataR1.setType1(DataR_TYPE.TYPE_SHOP_BANNER.getValue());
            dataRService.delBy(dataR1);

            for (String id : ids) {
                DataR dataR = new DataR();
                dataR.setTargetId(Integer.valueOf(id));
                dataR.setSourceId(arg.getId());
                dataR.setType1(DataR_TYPE.TYPE_SHOP_BANNER.getValue());
                list2.add(dataR);
            }
            dataRService.addBatch(list2);
        }


        sysLogService.log("修改", request, Integer.valueOf(arg.getId()), Action.offerType);
        res = new BaseResult(true, 1);
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "/updatePlain", method = RequestMethod.POST)
    public BaseResult updatePlain(OfferVo arg, HttpSession session, HttpServletRequest request) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        depService.updateByPrimaryKeySelective(arg);
        return new BaseResult(true, 1);
    }

    /***
     * 分页查询
     * @param arg
     * @return
     */

    @ResponseBody
    @RequestMapping(value = "/query", method = RequestMethod.GET)
    public ListResult query(OfferVo arg, HttpSession session) {
        List<OfferVo> list = depService.queryByPage(arg);
        int total = depService.queryCount(arg);
        Pagination page = new Pagination(arg.getPage(), total, arg.getSize());
        ListResult res = new ListResult(true, list);
        res.setPage(page);
        return res;
    }


}
